﻿using System;
using System.ServiceModel;

namespace LayeredArchitectureSample.Infrastructure.Services
{
    /// <summary>
    /// Utility methods for dealing with WCF client channels.
    /// </summary>
    public static class ClientChannel
    {
        /// <summary>
        /// Closes the channel
        /// </summary>
        /// <remarks>
        /// This method is used to conveniently clean up client channels. It
        /// is necessary because HTTP-based channels hold a resource on the
        /// server side, and without being properly closed, clients can cause
        /// the servers to hang until old connections time out.
        /// </remarks>
        /// <param name="channel">The channel to close.</param>
        public static void ClientChannelDispose(object channel)
        {
            IClientChannel icc = channel as IClientChannel;

            if (icc == null)
            {
                throw new ArgumentException("Expecting an instance implementing IClientChannel", "channel");
            }

            try
            {
                icc.Close();
            }
            catch (CommunicationObjectFaultedException)
            {
                icc.Abort();
            }
            catch (TimeoutException)
            {
                icc.Abort();
            }
        }
    }
}